import * as moment from 'moment';
import consumerRecoderModel from "../model/consumerRecoderModel";
import storeRecoderModel from "../model/storeRecoderModel";
import visitMonthPlanModel from "../model/visitMonthPlanModel";
import formDataService from "./formDataService";
import emplModel from '../model/empl2Model';
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
//领导-计划页面
class DataToLeaderService {
    constructor() {}


    //领导模糊搜索某些员工的统计数据
    //userid:领导id month:月份  character:模糊字段
    async fuzzySearch(leaderId:string, character: string) {
        let json: any[]= [];
        let month=moment().format('MM')
        let access_token=await dTalkApiUtil.getAccessToken();
        // console.log('month:', month , '-------------character:',character,'------------->',leaderId,'2');
        let data=await formDataService.getAuthrity(leaderId,access_token)
        let sonData=await formDataService.getsonDept(data.leaderDepts,true,access_token,[])
        let son_list=sonData.list
        // let year=moment().format('YYYY')
        // let userIdArray = await visitMonthPlanModel.distinct("userId", {year:year,"$and":[{deptId:{$in:son_list}},{user: {$regex:character }}] , month: month });
        let userIdArray = await visitMonthPlanModel.distinct("userId", {"$and":[{deptId:{$in:son_list}},{user: {$regex:character }}] , month: month });
        if(userIdArray.length>0){
            for (let index = 0; index < userIdArray.length; index++) {
                let element = userIdArray[index];//element=userId 员工id
                if(element==leaderId){
                    continue;
                }else{
                    //统计数据
                    // (1)统计一个员工每月已拜访现有客户的数量
                    let visitedConsumerCount = await consumerRecoderModel.count({ planType: '现有客户', userid: element, month: month });
                    //(2)统计一个员工每月已拜访新客户的数量
                    let visitedNewConsumerCount = await consumerRecoderModel.count({ planType: '新拓展客户', userid: element, month: month });
                    //(3)统计一个员工每月开会的次数
                    let meetingCount = await visitMonthPlanModel.count({ meeting: '开会', userId: element, month: month });
                    //(4)统计一个员工每月休假的次数
                    let restCount = await visitMonthPlanModel.count({ rest: '休假', userId: element, month: month });
                    // let visitedConsumerCount = await consumerRecoderModel.count({year:year, planType: '现有客户', userid: element, month: month });
                    // let visitedNewConsumerCount = await consumerRecoderModel.count({year:year, planType: '新拓展客户', userid: element, month: month });
                    // let meetingCount = await visitMonthPlanModel.count({year:year, meeting: '开会', userId: element, month: month });
                    // let restCount = await visitMonthPlanModel.count({year:year, rest: '休假', userId: element, month: month });
                    let user_data=await visitMonthPlanModel.findOne({userId:element})
                    // let userInfo = await dTalkApi.getUserDetail(element);
                    json[index] = {
                        userid: element,//员工的id(隐藏)
                        userName: user_data.user,//员工名字
                        avatar: user_data.avatar,
                        // userName: userInfo.name,//员工名字
                        // avatar: userInfo.avatar,
                        visitedCurrentConsumer: '拜访现有客户' + visitedConsumerCount + '次',
                        visitedNewConsumer: '拜访新客户' + visitedNewConsumerCount + '次',
                        rest: '请假' + restCount + '次',
                        meeting: '开会' + meetingCount + '次'
                    }
                }
            }
        } 
        // console.log(json,'<--------------------')
        return json;
    }

    //向领导显示某个员工的今日计划内容----领导计划-今日计划页面
    //userid:员工id name:员工姓名
    async showNowdayplanToLeader(userid: string) {
        //  console.log('员工id:' + userid + '--------');
        let nowday_date = moment().format('YYYY-MM-DD');
        let recoder_list: any = [];
        let json: any = {};
        let data = await visitMonthPlanModel.find({ userId: userid, planDate: nowday_date,"$or":[{comment:1,planStatus:{$ne:'同意'}},{comment:2,planStatus:'申请取消',cancelApply:'否'},{comment:2,planStatus:{$ne:'同意'},cancelApply:'是'},{planStatus:'写好拜访记录'},{planStatus:'未写拜访记录'}]});
        for (let dataindex = 0; dataindex < data.length; dataindex++) {
            let element = data[dataindex];
            let recoderDetail: any = '';
            if (!element.visitRecoder) {
                recoderDetail = '';
            } else {
                if (element.plantype == '门店') {
                    recoderDetail = await storeRecoderModel.findById({ _id: element.visitRecoder });
                } else {
                    recoderDetail = await consumerRecoderModel.findById({ _id: element.visitRecoder });
                }
            }
            recoder_list.push({
                id: element._id,
                visitRecoder: recoderDetail,
                planDate: element.planDate,
                consumerName: element.consumerName,
                consumerCode: element.consumerCode,
                customerType: element.customerType,
                plantype: element.plantype,
                planStatus: element.planStatus,
                purpose: element.purpose,
                userId: element.userId,
                comment: element.comment,
                cancelApply: element.cancelApply,
                remark: element.remark
            })
        }
        let storeRate_ =await formDataService.getReachStoreRate_one_employeeDate1ToDate2(userid,nowday_date,nowday_date)
        let storeRate = storeRate_.toFixed(2);
        //今日计划的总条数
        let planTotalCount = await visitMonthPlanModel.count({ userId: userid, planDate: nowday_date, "$or": [{ comment: 1, planStatus: { $ne: '同意' } }, { comment: 2, planStatus: '申请取消', cancelApply: '否' }, { comment: 2, planStatus: { $ne: '同意' }, cancelApply: '是' }] });
        //统计一个员工一天的达成客户多少家
        let reachConsumerCount = await consumerRecoderModel.count({ userid: userid, planDate: nowday_date });
        let countReachStore = await storeRecoderModel.count({ userid: userid, planDate: nowday_date });
        let reacheTotalCount = countReachStore + reachConsumerCount;
        //客户拜访达成率
        let consumerRate_ = 0;
        if (planTotalCount == 0) {
            consumerRate_ = 0;
        } else {
            consumerRate_ = (reacheTotalCount / planTotalCount) * 100;
        }
        let consumerRate = consumerRate_.toFixed(2);
        //统计一个员工一天已经拜访的门店有多少家
        let countVisitedStore = await storeRecoderModel.count({ userid: userid, date: nowday_date, planType: '门店' });
         // let userInfo = await dTalkApi.getUserDetail(userid);
        let data_2=await visitMonthPlanModel.findOne({userId:userid})
        json = {
            header: {
                one: '计划' + planTotalCount + '家,|达成' + reacheTotalCount + '家',
                two: '客户拜访达成率' + consumerRate + '%',
                three: '已拜访门店' + countVisitedStore,
                four: '门店达标率' + storeRate + '%'
            },
            userid: userid,//员工id
            name: data_2.user,//员工姓名
            // name: userInfo.name,//员工姓名
            plandate: nowday_date,//拜访日期
            visitList: recoder_list  //拜访的客户的列表
        }
        return json;
    }


    async checkAllUserDataByMonth(leaderId: string, month: string) {
        console.log('领导的userid是:' + leaderId + '----月份:' + month);
        let access_token=await dTalkApiUtil.getAccessToken();
        let json: any = [];
        let data=await formDataService.getAuthrity(leaderId,access_token)
        let sonData=await formDataService.getsonDept(data.leaderDepts,true,access_token,[])
       // console.log(data,'<------------data')
        let son_list = sonData.list;
        let arr=await emplModel.distinct('userId',{});
        let employeeIdList = await visitMonthPlanModel.distinct("userId", { deptId: { $in: son_list },userId:{$in:arr} });
        for (let index_ = 0; index_ < employeeIdList.length; index_++) {
            let employee = employeeIdList[index_];//员工id
            if (employee == leaderId) {
                continue;
            } else {
                //查询员工姓名
                let data2=await visitMonthPlanModel.findOne({userId:employee,user:{$ne:null}})
                //统计数据
                // (1)统计一个员工每月已拜访现有客户的数量
                let visitedConsumerCount = await consumerRecoderModel.count({ planType: '现有客户', userid: employee, month: month,comment:2 });
                //(2)统计一个员工每月已拜访新客户的数量
                let visitedNewConsumerCount = await consumerRecoderModel.count({ planType: '新拓展客户', userid: employee, month: month,comment:2 });
                //(3)统计一个员工每月开会的次数
                let meetingCount = await visitMonthPlanModel.count({ meeting: '开会', userId: employee, month: month });
                //(4)统计一个员工每月休假的次数
                let restCount = await visitMonthPlanModel.count({ rest: '休假', userId: employee, month: month });
                // let visitedConsumerCount = await consumerRecoderModel.collection.countDocuments({year:year, planType: '现有客户', userid: element, month: month });
                // let visitedNewConsumerCount = await consumerRecoderModel.collection.countDocuments({year:year, planType: '新拓展客户', userid: element, month: month });
                // let meetingCount = await visitMonthPlanModel.collection.countDocuments({year:year, meeting: '开会', userId: element, month: month });
                // let restCount = await visitMonthPlanModel.collection.countDocuments({year:year, rest: '休假', userId: element, month: month });
                json.push({
                    userid:employee,//员工的id(隐藏)
                    userName: data2.user,
                    avatar: data2.avatar,
                    visitedCurrentConsumer: '拜访现有客户' + visitedConsumerCount + '次',
                    visitedNewConsumer: '拜访新客户' + visitedNewConsumerCount + '次',
                    rest: '请假' + restCount + '次',
                    meeting: '开会' + meetingCount + '次'
                })
            }
        }
        console.log(json,'json_json_json')
        return json;
    }












}
let dataToLeader = new DataToLeaderService();
export default dataToLeader;